package com.example.a.compressordemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import id.zelory.compressor.Compressor;

public class MainActivity extends AppCompatActivity {
    private ImageView src;
    private ImageView dst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String url = "http://cn.bing.com/az/hprichbg/rb/Dongdaemun_ZH-CN10736487148_1920x1080.jpg";
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/123.jpg";
        String path2 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/1234.jpg";
        Bitmap dst1;
        src = findViewById(R.id.src);
        dst = findViewById(R.id.dst);
        Glide.with(MainActivity.this).load(R.drawable.x1).into(src);
        try {
            dst1 = new Compressor(this).compressToBitmap((new File(path)));
            ByteArrayOutputStream  outputStream = new ByteArrayOutputStream();
            dst1.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
            Glide.with(MainActivity.this).load(outputStream.toByteArray()).into(dst);
            // Toast.makeText(MainActivity.this, "" + dst1.length(), Toast.LENGTH_SHORT).show();
            saveBitmapToSd(dst1,path2);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public static boolean saveBitmapToSd(Bitmap bitmap, String filePath) {
        FileOutputStream outputStream = null;
        try {
            File file = new File(filePath);
            if (file.exists() || file.isDirectory()) {
                file.delete();
            }
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        } catch (IOException e) {

            return false;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    
}
